//
//  NetworkTools.swift
//  SinaWeibo
//
//  Created by 郭平 on 15/10/8.
//  Copyright © 2015年 郭平. All rights reserved.
//

import UIKit
import AFNetworking

private let APP_ROOT_URL = "https://api.weibo.com/"

enum HTTPMethod: String {
    case POST = "POST"
    case GET = "GET"
}

class NetworkTools: AFHTTPSessionManager {

    
    //应用信息
    let WB_client_id = "2937096105"
    let WB_redirect_uri = "http://www.baidu.com"
    let WB_client_secret = "e9db26ff4c756c6cb6f82141c2a78e94"
    
    // 单例对象
    static let shatedToos: NetworkTools = {
        
        let url = NSURL(string: APP_ROOT_URL)
        let tools = NetworkTools(baseURL: url)
        // 追加解析
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    // 请求oauth
    func OAuthURL() -> NSURL {
        
        let pageURL = "https://api.weibo.com/oauth2/authorize"
        let urlString = pageURL + "?" + "client_id=" + WB_client_id + "&redirect_uri=" + WB_redirect_uri
        return NSURL(string: urlString)!
    }
    
    // 请求用户token
    func loadAccessToken(code:String, completion:(dict:[String : AnyObject]? , error: NSError?) -> ()){
        
        let urlString = "oauth2/access_token"
        let pramas = ["client_id":WB_client_id,"client_secret":WB_client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":WB_redirect_uri]
        
        requestJSON(.POST, urlString: urlString, parmas: pramas, completion: completion)
    }
    
    // 请求用户信息
    func loadUserInfo(accessToken: String, uid: String, completion:(dict: [String : AnyObject]?, error: NSError?)->()){
        
        let urlString = "2/users/show.json"
        let params = [
            "access_token":accessToken,
            "uid":uid
        ]
        requestJSON(.GET, urlString: urlString, parmas: params, completion: completion)
    }
    
    // 请求数据
    func loadData(paramas: [String : AnyObject]?, completion:(dict:[String : AnyObject]?, error: NSError?)->()) {
        
        let urlString = "2/statuses/friends_timeline.json"
        
        requestJSON(.GET, urlString: urlString, parmas: paramas, completion: completion)
    }
    
    
    /**
     封装AFN网络请求
    
    - parameter method:     <#method description#>
    - parameter urlString:  <#urlString description#>
    - parameter parmas:     <#parmas description#>
    - parameter completion: <#completion description#>
    - parameter error:      <#error description#>
    */
   private func requestJSON(method:HTTPMethod, urlString: String, parmas: [String : AnyObject]? = nil,completion:(dict:[String : AnyObject]?,error: NSError?) -> ()) {
    
        let successCallBack = {(tast:NSURLSessionDataTask, result:AnyObject) -> () in
        
            if let info = result as? [String : AnyObject] {
                
                completion(dict: info, error: nil)
                
//                printLog(info)
                
            } else {
            
                completion(dict: nil, error: NSError(domain: "com.baidu.dataerror", code: -1000, userInfo: ["error" : "数据不合法"]))
            }
        }
    
        let failureCallBack = {(task:NSURLSessionDataTask, error:NSError) -> () in
            
            completion(dict: nil, error: error)
            
            printLog(error)
        }
    
        if method == HTTPMethod.GET {
            
            GET(urlString, parameters: parmas, success: successCallBack, failure: failureCallBack)
        }else{
            
            POST(urlString, parameters: parmas, success: successCallBack, failure: failureCallBack)
        }
    }
}
